﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NaturalNote.Core.Database
{
    public class XTable<T> where T : class, new()
    {
        private XTable() { this.Init(); }

        public static XTable<T> Instance { get { return Nested.instance; } }

        private class Nested
        {
            //Explicit static constructor to tell C# compiler
            //not to mark type as beforefieldinit
            static Nested()
            {

            }

            internal static readonly XTable<T> instance = new XTable<T>();
        }
        private readonly TableInfo tableInfo = new TableInfo();
        private void Init()
        {
            var type = typeof(T);
            var tableAttrs = type.GetCustomAttributes(false);
            foreach (var item in tableAttrs)
            {
                if (item is TableAttribute tableAttribute)
                {
                    this.tableInfo.Name = string.IsNullOrWhiteSpace(tableAttribute.Name) ? type.Name : tableAttribute.Name;
                    break;
                }
            }
            var props = type.GetProperties();
            foreach (var prop in props)
            {
                var columnAttrs = prop.GetCustomAttributes(false);
                foreach (var item in columnAttrs)
                {
                    if (item is ColumnAttribute columnAttribute)
                    {
                        var columnInfo = new ColumnInfo();
                        columnInfo.Name = string.IsNullOrWhiteSpace(columnAttribute.Name) ? prop.Name : columnAttribute.Name;
                        columnInfo.IsPrimary = columnAttribute.IsPrimary;
                        columnInfo.PropName = prop.Name;
                        tableInfo.Columns.Add(columnInfo);
                        break;
                    }
                }
            }
        }
        public TableInfo TableInfo
        {
            get { return tableInfo; }
        }
    }
}
